import * as _ from "lodash"
import { PageList } from "../data"
import httpClient from "../httpclient"
import { Gender } from "../identity"

export class Member {
  public id: string
  public nickname: string
  public gender: Gender
  private store_id: string
  private country_code: string
  public phone: string
  public birthdate: string
  public tags: string[]
  public notes: string
  private joined_time: string

  public get storeId() {
    return this.store_id
  }

  public set storeId(storeId) {
    this.store_id = storeId
  }

  public get countryCode() {
    return this.country_code
  }

  public set countryCode(countryCode) {
    this.country_code = countryCode
  }

  public get joinedTime() {
    return this.joined_time
  }

}


class MemberQuery {
  private params = {}

  public page(page: number) {
    this.params["page"] = page
    return this
  }

  public limit(limit: number) {
    this.params["limit"] = limit
    return this
  }

  public storeId(storeId: string) {
    this.params["store_id"] = storeId
    return this
  }

  public path(path: string) {
    this.params["path"] = path
    return this
  }

  public list(): Promise<PageList<Member>> {
    return httpClient.get(`/v1/stores/${this.params["store_id"]}/members`, { params: this.params })
      .then(({ data }) => {
        return _.assign(PageList.empty(), data, {
          elements: _.map(data.elements, element => _.assign(new Member(), element)),
        })
      })
  }
}

export class MemberServiceV1 {

  public static addMember(member: Member): Promise<Member> {
    return httpClient.post(`/v1/stores/${member.storeId}/members`, member)
      .then(({ data }) => _.assign(new Member(), data))
  }

  public static getMember(storeId: string, memberId: string): Promise<Member> {
    return httpClient.get(`/v1/stores/${storeId}/members/${memberId}`)
      .then(({ data }) => _.assign(new Member(), data))
  }

  public static getMembers(): MemberQuery {
    return new MemberQuery()
  }

  public static updateMember(member: Member): Promise<Member> {
    return httpClient.patch(`/v1/stores/${member.storeId}/members/${member.id}`, member)
      .then(({ data }) => _.assign(new Member(), data))
  }

  public static deleteMember(storeId: string, memberId: string): Promise<void> {
    return httpClient.delete(`/v1/stores/${storeId}/members/${memberId}`)
  }
}
